package com.mdlib.helper.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTabHost;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.ljlib.core.base.BaseActivity;
import com.ljlib.core.util.LogUtil;
import com.ljlib.help.R;
import com.mdlib.helper.api.DataManager;
import com.mdlib.helper.api.MDUpDateApp;
import com.mdlib.helper.api.network.RxHelper;
import com.mdlib.helper.api.network.RxSubscribe;
import com.mdlib.helper.event.LocationEvent;
import com.mdlib.helper.model.AccountModel;
import com.mdlib.helper.model.AppModel;
import com.mdlib.helper.model.BaseResult;
import com.mdlib.helper.model.entity.AppLocationEntity;
import com.mdlib.helper.module.location.LocationHelper;
import com.mdlib.helper.module.location.LocationView;
import com.mdlib.helper.ui.UIHelper;
import com.mdlib.helper.ui.fragments.home.RushHomeFragment;
import com.mdlib.helper.ui.fragments.home.RushMyOrdersFragment;
import com.mdlib.helper.ui.fragments.home.SendHomeFragment;
import com.mdlib.helper.ui.fragments.home.SendMyOrdersFragment;
import com.mdlib.helper.ui.fragments.rush.me.RushMeFragment;
import com.mdlib.helper.ui.fragments.sect.send.SendMeFragment;
import com.mdlib.helper.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import butterknife.Bind;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

public class MainActivity extends BaseActivity implements LocationView {

    private LayoutInflater mLayoutInfalter;
    private Handler mLocationHandler = new Handler();

    @Bind(android.R.id.tabhost)
    FragmentTabHost mTabHost;
    private LocationHelper locationHelper;
    public static final int locationTime = 300000;
    public static boolean mPushType;
    /**
     * 下单
     */
    private Class mFragmentArray[] = {SendHomeFragment.class, SendMyOrdersFragment.class, SendMeFragment.class};
    private int mImageViewArray[] = {R.drawable.tab_send_image_bg, R.drawable.tab_order_image_bg, R.drawable.tab_me_image_bg};
    private String mTextviewArray[] = {"发单", "订单", "我的"};

    /**
     * 抢单
     *
     * @param savedInstanceState
     */
    private Class mFragmentArrays[] = {RushHomeFragment.class, RushMyOrdersFragment.class, RushMeFragment.class};
    private int mImageViewArrays[] = {R.drawable.tab_rush_image_bg, R.drawable.tab_order_image_bg, R.drawable.tab_me_image_bg};
    private String mTextviewArrays[] = {"抢单", "订单", "我的"};
    private String roleType = AccountModel.getInstance().getRoleType();
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            try {
                if (locationHelper != null) {
                    locationHelper.onSart();
                }
                mLocationHandler.postDelayed(runnable, locationTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        if (locationHelper != null) {
            locationHelper.onStop();
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationHelper != null) {
            locationHelper.onDestory();
        }
        unSubscribe();
    }

    @Override
    protected void initView() {
        locationHelper = new LocationHelper(MainActivity.this, this);
        if (locationHelper != null) {
            locationHelper.onSart();
        }
        mLayoutInfalter = LayoutInflater.from(this);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.contentPanel);
        int fragmentCount;
        if (roleType.equals("user")) {
            fragmentCount = mFragmentArray.length;
            for (int i = 0; i < fragmentCount; i++) {
                TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i]).setIndicator(getTabItemView(i));
                mTabHost.addTab(tabSpec, mFragmentArray[i], null);
                mTabHost.getTabWidget().setDividerDrawable(null);
            }
        } else if (roleType.equals("run")) {
            fragmentCount = mFragmentArrays.length;
            for (int i = 0; i < fragmentCount; i++) {
                TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArrays[i]).setIndicator(getTabItemView(i));
                mTabHost.addTab(tabSpec, mFragmentArrays[i], null);
                mTabHost.getTabWidget().setDividerDrawable(null);
            }
            mLocationHandler.postDelayed(runnable, locationTime);
        }
        LogUtil.e("更新：");
        MDUpDateApp.upDateApp(MainActivity.this, false);

    }
    @Override
    protected void onResume() {
        super.onResume();
        mPushType = true;
    }


    @Override
    protected void onPause() {
        super.onPause();
        mPushType = false;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        boolean flag = this.getIntent().getBooleanExtra("history",false);
        if (flag) {
            mTabHost.setCurrentTab(1);
        }
    }

    private View getTabItemView(int index) {
        View view = mLayoutInfalter.inflate(R.layout.tab_content, null);

        ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
        TextView textView = (TextView) view.findViewById(R.id.textview);

        if (roleType.equals("user")) {
            imageView.setImageResource(mImageViewArray[index]);
            textView.setText(mTextviewArray[index]);
        } else if (roleType.equals("run")) {
            imageView.setImageResource(mImageViewArrays[index]);
            textView.setText(mTextviewArrays[index]);
        }

        return view;
    }


    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            //两秒之内按返回键就会退出
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtil.showToast(getResources().getString(R.string.tips_exit_out_app));
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void showLocation(AMapLocation location) {
        if (location != null) {
            LogUtil.e("地址: " + location.toString());
            AppModel.getInstance().setAppLocationEntity(new AppLocationEntity(String.valueOf(location.getLatitude()),
                    String.valueOf(location.getLongitude()), location.getStreet(), location.getCity()));
            AppModel.getInstance().writeToCache();
            EventBus.getDefault().postSticky(new LocationEvent("0"));
        }
        if(roleType.equals("run")){
            LogUtil.e("runsendTude");
            location.getLatitude();
            location.getLongitude();
            sendTude(location.getLatitude() + "", location.getLongitude() + "");
        }
    }

    private void sendTude(String Latitude,String Longitude){
        addSubscribe(DataManager.getInstance().getUserApi()
                .sendTude(Latitude,Longitude).compose(RxHelper.<BaseResult>rxSchedulerHelper())
                .subscribe(new RxSubscribe<BaseResult>() {
                    @Override
                    protected void onSucc(BaseResult baseResult) {
                          LogUtil.e(baseResult.toString());
                    }

                    @Override
                    protected void onFail(String msg) {
                        LogUtil.e(msg);
                    }
                }));

    }


    private CompositeSubscription compositeSubscription;

    public void addSubscribe(Subscription subscription) {
        if (compositeSubscription == null) {
            compositeSubscription = new CompositeSubscription();

        }
        compositeSubscription.add(subscription);
    }

    public void unSubscribe() {
        if (compositeSubscription != null) {
            compositeSubscription.unsubscribe();
            compositeSubscription = null;
        }
    }

}
